﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Linq;
using System.Text;

namespace SOEI.Solution.Helper
{
    public class ParamCollect : List<ParamItem>
    {
        public ParamCollect()
        {
        }

        public ParamCollect(IEnumerable<ParamItem> collection) : base(collection)
        {
        }

        public ParamCollect(int capacity) : base(capacity)
        {
        }

        public ParamItem this[string name]
        {
            get
            {
                return this.FirstOrDefault(a => (a.Name + "").ToUpper() == (name + "").ToUpper());
            }
        }

        /// <summary>从对象中分析参数
        /// </summary>
        public static ParamCollect FromObj(object pObj, ParameterDirection pDirection = ParameterDirection.Input)
        {
            ParamCollect vRes = null;

            if (pObj != null)
            {
                vRes = new ParamCollect();

                var vProps = pObj.GetType().GetProperties();

                foreach (var vProp in vProps)
                {
                    vRes.Add(new ParamItem()
                    {
                        Name = vProp.Name,
                        Value = vProp.GetValue(pObj),
                        Direction = pDirection
                    });
                }
            }

            return vRes;
        }

        /// <summary>给现有参数集合增加从对象分析参数
        /// </summary>
        public void AddFromObj(object pObj, ParameterDirection pDirection = ParameterDirection.Input)
        {
            if (pObj != null)
            {
                var vProps = pObj.GetType().GetProperties();

                foreach (var vProp in vProps)
                {
                    this.Add(new ParamItem()
                    {
                        Name = vProp.Name,
                        Value = vProp.GetValue(pObj),
                        Direction = pDirection
                    });
                }
            }
        }
        
        /// <summary>添加参数名称与参数方向
        /// </summary>
        public void Add(string pName, ParameterDirection pDirection)
        {
            this.Add(new ParamItem(pName, pDirection));
        }

        public dynamic GetDynamic()
        {
            dynamic obj = new ExpandoObject();
            IDictionary<string, object> dict = obj as IDictionary<string, object>;

            foreach (var item in this)
            {
                dict[item.Name] = item.Value;
            }

            return obj;
        }
    }
}
